|
|
|
|
|
|
|
A function's return value can be used in several different ways. It can be assigned to a variable as just shown, or the function call can be used in a statement as shown in the following: |
|
|
|
|
|
|
|
|
If CalcTotal <= 0 Then
Msgbox Invalid Sale Amount Entered
End If |
|
|
|
|
|
|
|
|
When you create subroutines and functions, which type of routine you will create depends on whether you need a value returned. In Visual Basic, you can use several built-in functions either as a subroutine or as a function. Visual Basic figures out which way to process the routine based on its position in the code. As an example, here are two lines of code using a MsgBox. One is a subroutine and the other is a function. |
|
|
|
|
|
|
|
|
If Msgbox(Do you want to continue?, vbQuestion + vbYesNo, App.Title)
= vbYes Then
Msgbox We will continue processing the data
End If |
|
|
|
|
|
|
|
|
If a routine is used as a value as in the previous If statement, it is assumed to be a function. However, if no return value is expected, then it is assumed to be a subroutine. Unfortunately, you cannot create a routine that is both a subroutine and a function. |
|
|
|
|
|
|
|
|
You must understand only one other important issue about passing variables: how the passed data is referenced. There are two ways to reference data, by value and by reference. By default, all Visual Basic routines pass data by reference, which means that the arguments can be changed by their receiving routines. If you want to keep the data from being changed in the receiving routine, you must pass the arguments by value instead of by reference. To pass an argument by value, you would add the ByVal keyword in front of a parameter in the receiving routine's declaration statement, as shown in the following: |
|
|
|
|
|
|
|
|
Public Sub CalcTotal (ByVal Qty, ByVal Price) |
|
|
|
|
|
|
|
|
When you are passing a variable by reference, the subroutine is actually working with the data variable from the calling routine. In contrast, passing variables by value will pass the actual data to the receiving routine, and it will be placed into a local variable in that routine. To see the difference between these, start a new project, add two command buttons to the form, and then copy the code in Listing 6.2 to the project's code section. |
|
|
|
|
|